<template>
  <div class="home">
    <!-- 使用topology组件 -->
    <topology :configs="topologyConfigs" :materials="materials" :user="user" :data="data" @event="onEvent"></topology>

    <YKdialog ref="ykRef"></YKdialog>
    <YTdialog ref="ytRef"></YTdialog>

    <el-dialog :title="FangZhenTitle" :visible.sync="FangZhenDialogVisible" :width="DialogWidth"
      :close-on-click-modal="false" center custom-class="myClass" :fullscreen="isFullscreen">
      <div slot="title" class="headertitle">
        <span>{{ FangZhenTitle }} </span>
        <i class="el-icon-full-screen" @click="fullscreen"></i>
      </div>
      <timeReport :body="body" :header="header" :tableHeight="maxheight" :loadingShow="loadingShow"
        :getBodyData="getBodyData" :bodyConfigList="bodyConfigList"></timeReport>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
// 导入topology-vue组件
import topology from "topology-vue";
// 需要导入topology-vue.css
import "topology-vue/topology-vue.css";
// import { register as registerMyShape } from "../../utils/topolpgy/custom/myShape";
Vue.use(topology);
import {
  defalutMenus,
  defalutUserMenus,
  defalutMaterials,
  defalutMaterialTabs,
} from "../../utils/topolpgy/data";

// import { drawNodeFns } from "@topology/core";

import { DataMessage } from "@/utils/topolpgy/msg";
import timeReport from "@/components/Topology/timeReport.vue";
import YTdialog from "@/components/Topology/YTdialog.vue";
import YKdialog from "@/components/Topology/YKdialog.vue";
import IndexDBCache from "@/utils/indexedDB";
import {
  setMessageCallback,
  removeMessageCallback,
  getGuid32,
  publishMsg,
  checkSpecialId,
} from "@/mqtt";
import "@/utils/dialog";
import axios from "axios";
import { getStorageItem } from "@/utils/storage";

export default {
  name: "TopologyIndex",
  components: {
    timeReport,
    YTdialog,
    YKdialog,
  },
  data() {
    return {
      FangZhenDialogVisible: false, //方阵
      topologyConfigs: {
        license: {
        },
        logo: null,
        menus: defalutMenus,
        userMenus: defalutUserMenus,
        materialTabs: defalutMaterialTabs,
      },
      user: {
        username: "云港",
      },
      materials: {
        system: [],
        user: [],
        topology: [],
      },
      data: {},
      datafrom: {
        id: this.$route.query.id,
      },
      name: "",
      body: [],
      header: [],
      bodyConfigList: [],
      loadingShow: false,
      mySpecialId: "",
      getBodyData: false,
      FangZhenTitle: "",
      isFullscreen: false,
      DialogWidth: "60%",
      maxheight: 300,
      flag: false,
      db: null,
    };
  },

  created() { },

  watch: {
    $route(val) {
      if (!val.query.hasOwnProperty("component")) {
        this.reqTopologyData();
        this.getMaterials();
      }
      // this.mounted();
    },
    isFullscreen() {
      this.isFullscreen
        ? (this.maxheight = window.innerHeight - 80)
        : (this.maxheight = 300);
    },
  },

  mounted() {
    this.initIndexDB();
    setMessageCallback(this.onMessage);
    window.topology.options.cacheLen = 3;
    // const data = window.topologyData;
    const data = window.topology.data;
    this.reqMyIotLicense();
    // 存在缓存数据，预览页返回
    if (data.pens.length > 0) {
      this.data = { data: Object.assign({}, data) };
      setTimeout(() => {
        window.topology.data.pens = [];
      }, 200);
    } else {
      // Do sth.
    }
    if (this.$route.query.hasOwnProperty("component")) {
      let getComponentnewMsg = {
        webMsgType: 1016,
        funCode: 13,
      };
      getComponentnewMsg.data = {
        id: this.$route.query.id,
      };
      publishMsg(getComponentnewMsg);
    } else {
      this.reqTopologyData();
    }

    // this.getMaterials();
    // 请确保 7777777(类似数字).js 和 rg.js已下载，正确加载
    if (window.registerTools) {
      window.registerTools();
      if (this.flag) {
        this.materials.system[0]["list"] = window.topologyTools;
      }
    }

    // console.log("没有注册之前", drawNodeFns);
    // registerMyShape();
    // console.log("注册之后", drawNodeFns);
    window.topology.on("node", this.onNodeMessage);

    // window.myFns = drawNodeFns;
  },
  destroyed() {
    removeMessageCallback(this.onMessage);
  },
  beforeDestroy() {
    this.getBodyData = false;
  },
  methods: {
    initIndexDB() {
      this.db = new IndexDBCache();
      this.db
        .initDB("topologyid")
        .then((res) => {
          if (res.type == "upgradeneeded") {
            console.log("indexDB数据库创建或更新成功");
          } else {
            console.log("indexDB数据库初始化成功");
          }
        })
        .catch((err) => {
          console.log("indexDB数据库初始化失败", err);
        });
    },
    fullscreen() {
      this.isFullscreen = !this.isFullscreen;
    },
    async getMaterials() {
      this.flag = false;

      // registerMyShape();
      // alert('getMaterials');
      // 注册图形库
      this.materials.system = [];
      for (var i = 0; i < defalutMaterials.length; i++) {
        this.materials.system.push(defalutMaterials[i]);
      }
      this.flag = true;
      // 国家电网图元规范
      this.materials.system.push({
        iconUrl: "/font/font_2395018_pl6jy69tbjr/iconfont.css", // 替换成真实的地址
        // iconUrl: "/public/font/font_2395018_pl6jy69tbjr/iconfont.css", // 替换成真实的地址
        show: true,
        list: [], // 此处留空数组就好，会自动填充
      });

      this.materials.system.push({
        iconUrl: "/font/font_2073009_ctn7qgh8t/iconfont.css", // 替换成真实的地址
        show: true,
        list: [], // 此处留空数组就好，会自动填充
      });

      this.materials.system.push({
        iconUrl: "//at.alicdn.com/t/font_2366205_nnqrrnc9mta.css", // 替换成真实的地址
        show: true,
        list: [], // 此处留空数组就好，会自动填充
      });

      this.materials.system.push({
        iconUrl: "/font/font_2052340_u3ww8v9eb5j/iconfont.css", // 替换成真实的地址
        show: true,
        list: [], // 此处留空数组就好，会自动填充
      });

      this.materials.system.push({
        iconUrl: "/font/font_2073009_u56zfo0voi/iconfont.css", // 替换成真实的地址
        show: true,
        list: [], // 此处留空数组就好，会自动填充
      });

      // console.log(this.materials, "图元");

      const images = await axios.get("/api/images");
      if (this.isJSONArray(images.data)) {
        for (let i = 0; i < images.data.length; i++) {
          images.data[i]["show"] = true;
          images.data[i]["expand"] = false;
          const subImages = images.data[i].list;

          for (let j = 0; j < subImages.length; j++) {
            subImages[j]["image"] = subImages[j]["url"];
            delete subImages[j]["url"];
          }
          this.materials.system.push(images.data[i]);
        }
      } else {
        console.log("不合法的图形库：", images.data);
      }
      // this.reqMyIotLicense();
      this.registerBuiness();
      // this.materials = Object.assign({}, this.materials);

      if (window.registerTools) {
        window.registerTools();
        if (this.flag) {
          this.materials.system[0]["list"] = window.topologyTools;
        }
      }
    },

    isValidJSON(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },

    isJSONArray(obj) {
      if (!Array.isArray(obj)) {
        return false; // 非数组
      }

      for (const element of obj) {
        if (typeof element !== 'string' &&
          typeof element !== 'number' &&
          typeof element !== 'boolean' &&
          typeof element !== 'object' &&
          !Array.isArray(element) &&
          element !== null) {
          return false; // 数组中有不符合 JSON 格式的元素
        }
      }

      return true; // 所有元素都符合 JSON 格式
    },

    isValidJSONObject(obj) {
      try {
        let str = JSON.stringify(obj);
        return isValidJSON(str);
      } catch (e) {
        return false;
      }
    },

    registerBuiness() {
      if (window.registerTools) {
        window.registerTools();
      }
      if (window.registerIot) {
        window.registerIot(this.topologyConfigs.license);
        // console.log("注册", this.topologyConfigs.license);
      }
      this.materials = Object.assign({}, this.materials);
    },

    onMessage(topic, msg) {
      // console.log(topic, msg);
      switch (msg.webMsgType) {
        case 1016:
          switch (msg.funCode) {
            case 3:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                } else {
                  if (msg.data.id == this.$route.query.val) {
                    this.name = msg.data.name;
                    if (msg.data.data) {
                      this.data = msg.data.data;
                    }
                  }
                }
                publishMsg({
                  webMsgType: 1016,
                  funCode: 7,
                });
                this.reqFullData();
              }
              break;
            case 4:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  this.$message.success("保存一次图数据成功");
                }
              }
              break;
            case 7:
              if (msg.retCode != 0 || !msg.data) {
                return this.$message.error(msg.retMsg);
              } else {
                this.materials.user = [];
                msg.data.forEach((e) => {
                  this.materials.user.push(e);
                });
                this.materials = Object.assign({}, this.materials);
              }
              break;
            case 8:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  this.$message.success(msg.retMsg);
                }
              }
              break;
            case 9:
              if (msg.retCode != 0) {
                return this.$message.error(msg.retMsg);
              } else {
                this.$message.success(msg.retMsg);
              }
              break;
            case 10:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  this.$message.success(msg.retMsg);
                }
              }
              break;
            case 11:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  this.$message.success(msg.retMsg);
                }
              }
              break;
            case 12:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  this.$message.success(msg.retMsg);
                }
              }
              break;
            case 13:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0) {
                  return this.$message.error(msg.retMsg);
                } else {
                  if (msg.data) {
                    this.data = msg.data;
                  }
                  // this.$message.success(msg.retMsg);
                }
              }
              break;
            case 14:
              this.topologyConfigs.license = msg.data;
              this.getMaterials();
              break;
            default:
              break;
          }
          break;
        case 1024:
          switch (msg.funCode) {
            case 7:
              // if (this.mySpecialId == msg["specialId"]) {
              if (msg.retCode != 0 || !msg.data) {
                this.$message.error(msg.retMsg);
              } else {
                this.body = msg.data.body;
                this.header = msg.data.header;
                this.header.forEach((e) => {
                  if (e.unit) {
                    e.name = e.name + "(" + e.unit + ")";
                  }
                });
                this.loadingShow = false;
                let id = msg.data.id;
                //发送报表配置预览
                let newMsg2 = {
                  webMsgType: 1024,
                  funCode: 8,
                };
                newMsg2.data = { id: id };
                this.mySpecialId = publishMsg(newMsg2);
              }
              // }
              break;
            case 8:
              // if (checkSpecialId) {
              if (msg.retCode != 0 || !msg.data) {
                this.$message.error(msg.retMsg);
              } else {
                this.bodyConfigList = msg.data.body;
                this.getBodyData = true;
              }
              // }
              break;
            default:
              break;
          }
          break;
        default:
          if (sessionStorage.getItem("topology_is_msg") == 1) {
            DataMessage.onMsg(window.topology, msg);
          }
          break;
      }
    },

    onEvent(e) {
      console.log(e);
      switch (e.name) {
        case "logout":
          // 退出登录
          break;
        case "view":
          window.topology.pens = [];
          this.$router.push({
            path: "/TopologyIndex",
            query: { component: true, name: e.params.folder, id: e.params.id },
          });
          this.data = e.params;
          break;
        case "openMaterialGroup":
          // 展开/折叠图标工具栏分组
          break;
        case "add-user-folder":
          // 添加“用户组建文件夹”
          let addnewMsg = {
            webMsgType: 1016,
            funCode: 8,
          };
          addnewMsg.data = {
            name: e.params,
          };
          publishMsg(addnewMsg);
          break;
        case "rename-user-folder":
          // 更改用户组建文件夹”
          let updatenewMsg = {
            webMsgType: 1016,
            funCode: 12,
          };
          updatenewMsg.data = {
            name: e.params.name,
            oldName: e.params.oldName,
          };
          publishMsg(updatenewMsg);
          break;
        case "remove-user-folder":
          // 删除用户目录组件

          let delnewMsg = {
            webMsgType: 1016,
            funCode: 9,
          };
          delnewMsg.data = {
            name: e.params.name,
          };
          publishMsg(delnewMsg);
          break;
        case "remove-user-component":
          // 删除我的组件
          let delcomponentnewMsg = {
            webMsgType: 1016,
            funCode: 11,
          };
          delcomponentnewMsg.data = {
            id: e.params.id,
          };
          publishMsg(delcomponentnewMsg);
          break;
        case "addMaterial":
          this.data.pens = [];
          this.$router.push({
            path: "/TopologyIndex",
            query: { component: true, name: e.params, id: Date.now() + "" },
          });
          // 添加“我的组件”
          break;
        case "editMaterial":
          // 编辑“我的组件”
          break;
        case "open":
          // 导航菜单configs.menus里面定义的action
          // 比如这里表示打开文件
          break;
        case "save":
          // 导航菜单configs.menus里面定义的action
          // 比如这里表示保存文件
          this.save();
          break;
        case "addImageUrl":
          // 在“我的图片”里面添加了一张新图片
          // this.addImageUrl(e.params);
          break;
        case "deleteImage":
          // 在“我的图片”里面删除了一张图片
          // this.deleteImage(e.params);
          break;
        case "preview":
          let source = window.topology.pureData();
          let target = { topologyid: this.$route.query.val };
          let topologyData = Object.assign(source, target);
          this.db
            .addData(topologyData)
            .then((res) => {
              console.log("写入indexDB数据库成功", res);
            })
            .catch((err) => {
              console.log("写入indexDB数据库失败", err);
            });
          this.$router.push({
            path: "/preview",
            query: { id: this.$route.query.val },
          });
          break;
      }
    },

    getImage(blob) {
      this.upload(blob);
    },

    async upload(blob, shared = false, filename = "/topology/thumb.png") {
      const form = new FormData();
      form.append("path", filename);
      form.append("randomName", "1");
      form.append("public", shared + "");
      form.append("file", blob);
      const ret = await axios.post("api/api/image", form);
      if (ret.data.error) {
        return null;
      }
      return ret.data.url;
    },

    save() {
      if (!this.$route.query.component) {
        // 保存一次图
        this.data = Object.assign({}, window.topology.pureData());
        if (!this.data.title) {
          this.data.title = `topology.${new Date().toLocaleString()}`;
        }
        let newMsg = {
          webMsgType: 1016,
          funCode: 4,
        };
        newMsg.data = {
          id: this.$route.query.val,
          name: this.name,
          data: this.data,
        };
        publishMsg(newMsg);
      } else {
        // 保存组件
        let imgUrl = window.topology.toImage(10, async (blob) => {
          let imageUrl = await this.upload(blob);
          this.data = Object.assign({}, window.topology.pureData());
          this.data.componentData = Object.assign(
            {},
            window.topology.toComponent()
          );
          this.data.image = imageUrl;
          let newMsg = {
            webMsgType: 1016,
            funCode: 10,
          };
          let objData = {
            id: this.$route.query.id,
            folder: this.$route.query.name,
          };
          let newData = Object.assign(this.data, objData);
          newMsg.data = newData;
          publishMsg(newMsg);
        });
      }
    },

    reqMyIotLicense() {
      let newMsg = {
        webMsgType: 1016,
        funCode: 14,
      };
      publishMsg(newMsg);
    },

    reqTopologyData() {
      let newMsg = {
        webMsgType: 1016,
        funCode: 3,
      };
      newMsg.data = { id: this.$route.query.val };
      publishMsg(newMsg);
    },

    reqFullData() {
      let newMsg = {
        webMsgType: 1007,
        funCode: 0,
      };
      publishMsg(newMsg);

      let newMsg1 = {
        webMsgType: 1008,
        funCode: 0,
      };
      publishMsg(newMsg1);

      let newMsg2 = {
        webMsgType: 1009,
        funCode: 0,
      };
      publishMsg(newMsg2);

      let newMsg3 = {
        webMsgType: 1010,
        funCode: 0,
      };
      publishMsg(newMsg3);

      let newMsg4 = {
        webMsgType: 1011,
        funCode: 0,
      };
      publishMsg(newMsg4);
    },

    onNodeMessage(pen) {
      let penData = pen.data;
      console.log(penData);
      if (penData != null) {
        const ctlData = penData;
        ctlData.name
          ? (this.FangZhenTitle = ctlData.name)
          : (this.FangZhenTitle = this.FangZhenTitle);
        ctlData.width
          ? (this.DialogWidth = ctlData.width)
          : (this.DialogWidth = this.DialogWidth);
        switch (ctlData.ctrl_type) {
          case 0:
            {
              this.$refs.ykRef.Ykdialog(ctlData);
            }
            break;
          case 1:
            {
              this.$refs.ytRef.Ytdialog(ctlData);
            }
            break;
          case 2:
            {
              this.getPerview(ctlData);
            }
            break;
        }
      }
    },
    getPerview(val) {
      //发送报表实时预览
      this.FangZhenDialogVisible = true;
      let newMsg1 = {
        webMsgType: 1024,
        funCode: 7,
      };
      newMsg1.data = { id: val.id };
      this.mySpecialId = publishMsg(newMsg1);
      this.loadingShow = true;
    },
  },
};
</script>
<style lang="scss">
.home {
  background: #fff;
  height: 100vh;
}

.myClass .el-dialog__header {
  background-color: rgba(0, 15, 52) !important;
  padding: 5px 20px 5px !important;

  .el-dialog__headerbtn {
    top: 8px;
  }

  // .el-dialog__title {
  //   color: #0a74ff96 !important;
  //   font-weight: 600;
  // }
  .headertitle {
    span {
      color: #0a74ff96 !important;
      font-size: 16px;
      font-weight: 600;
    }

    i {
      float: right;
      margin-top: 8px;
      margin-right: 25px;
      cursor: pointer;
    }
  }
}

.myClass .el-dialog__body {
  background-color: rgba(0, 15, 52);
  padding: 5px 20px;
}

.myClass .el-dialog {
  background-color: rgba(0, 15, 52);
}
</style>
